import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '@/api/index'
import { getStorage, setStorage } from '@/utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    refresh_token: '',
    user: JSON.parse(getStorage('user')) || {} // 用户基本资料(默认从本地取)
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      setStorage('token', token)
    },
    setRefreshToken (state, refreshToken) {
      state.refresh_token = refreshToken
      setStorage('refresh_token', refreshToken)
    },
    removeToken (state) {
      state.token = ''
      state.refresh_token = ''
    },
    setUser (state, userObj) {
      state.user = userObj
      setStorage('user', JSON.stringify(userObj))
    }
  },
  actions: {
    async loginAction (store, values) {
      try {
        const res = await loginAPI(values)
        store.commit('setToken', res.data.data.token)
        store.commit('setRefreshToken', res.data.data.refresh_token)

        return res // return到逻辑页面当中(async函数始终返回的是一个Promise对象，所以你的结果会被当做Promise对象成功的结果返回)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  getters: {
    userPhoto (state) {
      return state.user.photo
    }
  }
})
